import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/models/book/MaxScore.dart';
import 'package:ichinesereader/models/report/basketsResult.dart';
import 'package:ichinesereader/models/report/selfReadingData.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/dialogs/basketGradeDialog.dart';
import 'package:ichinesereader/widgets/dialogs/maxQuizDialog.dart';
import 'package:ichinesereader/widgets/dialogs/quizDialog.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';

// ignore: must_be_immutable
class SelfReadingDataGrid extends StatelessWidget {
  SelfReadingDataGrid(this.selfReadingItems, this.userName);

  List<SelfReadingItem> selfReadingItems;
  String userName;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();

  @override
  Widget build(BuildContext context) {
    Log.debug('build SelfReadingDataGrid');

    return this.selfReadingItems.isNotEmpty
        ? Column(children: [Expanded(child: _buildDataGrid(userName))])
        : Center(child: Text('Data not available ...'));
  }

  SfDataGrid _buildDataGrid(String userName) {
    return SfDataGrid(
      source: SelfReadingDataGridSource(
          items: selfReadingItems, userName: userName),
      onQueryRowHeight: (row) {
        return row.rowIndex == 0 ? 50.0 : 49.0;
      },
      //设置表头高度
      allowSorting: true,
      allowTriStateSorting: true,
      allowSwiping: false,
      controller: _dataGridController,
      navigationMode: GridNavigationMode.row,
      endSwipeActionsBuilder:
          (BuildContext context, DataGridRow row, int rowIndex) {
        return GestureDetector(
            onTap: () {},
            child: Container(
                color: Colors.redAccent,
                child: Center(
                  child: Icon(Icons.delete),
                )));
      },
      columns: <GridColumn>[
        GridColumn(
          width: 190,
          columnName: 'BookTitle',
          label: buildDataGridColumnLabel('BookTitle'),
        ),
        GridColumn(
          width: 160,
          columnName: 'Progress',
          label: buildDataGridColumnLabel('Progress'),
        ),
        GridColumn(
          columnName: 'Read',
          width: isWebOrDesktop ? 120 : 120,
          label: buildDataGridColumnLabel('Read'),
        ),
        GridColumn(
          columnName: 'Quiz',
          width: isWebOrDesktop ? 100 : 100,
          label: buildDataGridColumnLabel('Quiz'),
        ),
        GridColumn(
          columnName: 'MaxScore',
          width: isWebOrDesktop ? 160 : 160,
          label: buildDataGridColumnLabel('Highest Quiz Percentage'),
        ),
        GridColumn(
          columnName: 'Recording',
          width: isWebOrDesktop ? 140.0 : 140.0,
          label: buildDataGridColumnLabel('Recording'),
        ),
        GridColumn(
          columnName: 'Writing',
          width: isWebOrDesktop ? 120.0 : 120.0,
          label: buildDataGridColumnLabel('Writing'),
        ),
        GridColumn(
          columnName: 'When',
          width: 180,
          label: buildDataGridColumnLabel('Completed On'),
        ),
        GridColumn(
          columnName: 'BookId',
          width: 10,
          visible: false,
          label: buildDataGridColumnLabel('BookId'),
        ),
        GridColumn(
          columnName: 'UserName',
          width: isWebOrDesktop ? 120.0 : 120.0,
          visible: false,
          label: buildDataGridColumnLabel('UserName'),
        ),
        GridColumn(
          columnName: 'all',
          width: 10,
          visible: false,
          label: Container(
            alignment: Alignment.centerLeft,
            child: const Text(
              'all',
              style: TextStyle(
                fontFamily: 'Montserrat',
                color: Colors.black,
              ),
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ),
      ],
    );
  }
}

class SelfReadingDataGridSource extends DataGridSource {
  SelfReadingDataGridSource(
      {required List<SelfReadingItem> items, required String userName}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'BookTitle', value: dataGridRow.bookTitle ?? ''),
              DataGridCell<bool>(
                  columnName: 'Progress', value: dataGridRow.complete),
              DataGridCell<int>(
                  columnName: 'Read', value: dataGridRow.readCount),
              DataGridCell<int>(
                  columnName: 'Quiz', value: dataGridRow.quizCount),
              DataGridCell<MaxScore>(
                  columnName: 'MaxScore', value: dataGridRow.maxScore),
              DataGridCell<Writing>(
                  columnName: 'Recording', value: dataGridRow.recording),
              DataGridCell<Writing>(
                  columnName: 'Writing', value: dataGridRow.writing),
              DataGridCell<int>(columnName: 'When', value: dataGridRow.when),
              DataGridCell<String>(
                  columnName: 'BookId', value: dataGridRow.bookId ?? ''),
              DataGridCell<String>(columnName: 'UserName', value: userName),
              DataGridCell<SelfReadingItem>(
                  columnName: 'all', value: dataGridRow)
            ]))
        .toList();
  }

  final box = Hive.box('appconfig');

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    // bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
    //     Constants.NanhaiRole_Teacher;
    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Progress') {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                dataGridCell.value ? "Completed" : "In Progress",
                overflow: TextOverflow.ellipsis,
                style: Get.textTheme.bodySmall,
              ),
            );
          } else if (dataGridCell.columnName == "MaxScore") {
            var bookId = row
                .getCells()
                .where((element) => element.columnName == 'BookId')
                .first
                .value;
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: GestureDetector(
                onTap: () {
                  if (dataGridCell.value != null) {
                    showGeneralDialog(
                        context: Get.context!,
                        transitionDuration: Duration(milliseconds: 400),
                        pageBuilder: (bc, ania, anis) {
                          return MaxQuizDialog(
                            bookId: bookId,
                            maxScore: dataGridCell.value,
                          );
                        });
                  }
                },
                child: Text(
                  dataGridCell.value != null
                      ? "${dataGridCell.value.percentage}%"
                      : "--",
                  softWrap: true,
                  style: dataGridCell.value != null
                      ? Get.textTheme.titleLarge
                      : Get.textTheme.bodySmall,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            );
          } else if (dataGridCell.columnName == "Quiz") {
            var bookId = row
                .getCells()
                .where((element) => element.columnName == 'BookId')
                .first
                .value;
            var userName = row
                .getCells()
                .where((element) => element.columnName == 'UserName')
                .first
                .value;
            return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    if (dataGridCell.value > 0) {
                      showGeneralDialog(
                          context: Get.context!,
                          transitionDuration: Duration(milliseconds: 400),
                          pageBuilder: (bc, ania, anis) {
                            return QuizDialog(
                                bookId: bookId, userName: userName);
                          });
                    }
                  },
                  child: Text(
                    dataGridCell.value != null
                        ? dataGridCell.value.toString()
                        : "--",
                    softWrap: true,
                    style: dataGridCell.value != null && dataGridCell.value > 0
                        ? Get.textTheme.titleLarge
                        : Get.textTheme.bodySmall,
                    overflow: TextOverflow.ellipsis,
                  ),
                ));
          } else if (dataGridCell.columnName == "Recording") {
            String _status = "--";

            if (dataGridCell.value != null &&
                dataGridCell.value.location != null) {
              if (dataGridCell.value.status != null)
                _status = dataGridCell.value.status;
              else
                _status = 'NEW';
            }

            return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    if (dataGridCell.value != null) {
                      var basketItem = BasketItem();
                      basketItem.bookId = row
                          .getCells()
                          .where((element) => element.columnName == 'BookId')
                          .first
                          .value;
                      basketItem.contentType =
                          dataGridCell.columnName.toUpperCase();
                      basketItem.player = Player(
                          userName: row
                              .getCells()
                              .where(
                                  (element) => element.columnName == 'UserName')
                              .first
                              .value);
                      var _selfReadingItem = row
                          .getCells()
                          .where((element) => element.columnName == 'all')
                          .first
                          .value as SelfReadingItem;

                      basketItem.bookImageUrl = _selfReadingItem.bookImageUrl;

                      basketItem.content = Content(
                          grade: _selfReadingItem.recording?.grade ?? '',
                          comment: _selfReadingItem.recording?.comment ?? '',
                          location: _selfReadingItem.recording?.location ?? '');
                      basketItem.status = _selfReadingItem.recording?.status;

                      showGeneralDialog(
                          context: Get.context!,
                          transitionDuration: Duration(milliseconds: 0),
                          pageBuilder: (bc, ania, anis) {
                            return BasketGrade(
                              basketItem: basketItem,
                            );
                          });
                    }
                  },
                  child: Text(
                    _status,
                    softWrap: true,
                    style: _status != '--'
                        ? Get.textTheme.titleLarge
                        : Get.textTheme.bodySmall,
                    overflow: TextOverflow.ellipsis,
                  ),
                ));
          } else if (dataGridCell.columnName == "Writing") {
            String _status = '--';
            if (dataGridCell.value != null &&
                dataGridCell.value.status != null) {
              _status = dataGridCell.value.status;
            }

            return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    if (dataGridCell.value != null) {
                      var basketItem = BasketItem();
                      basketItem.bookId = row
                          .getCells()
                          .where((element) => element.columnName == 'BookId')
                          .first
                          .value;
                      basketItem.contentType =
                          dataGridCell.columnName.toUpperCase();
                      basketItem.player = Player(
                          userName: row
                              .getCells()
                              .where(
                                  (element) => element.columnName == 'UserName')
                              .first
                              .value);
                      var _selfReadingItem = row
                          .getCells()
                          .where((element) => element.columnName == 'all')
                          .first
                          .value as SelfReadingItem;

                      basketItem.bookImageUrl = _selfReadingItem.bookImageUrl;

                      basketItem.content = Content(
                          grade: _selfReadingItem.writing?.grade ?? '',
                          comment: _selfReadingItem.writing?.comment ?? '',
                          text: _selfReadingItem.writing?.text ?? '');
                      basketItem.status = _selfReadingItem.writing?.status;

                      showGeneralDialog(
                          context: Get.context!,
                          transitionDuration: Duration(milliseconds: 0),
                          pageBuilder: (bc, ania, anis) {
                            return BasketGrade(
                              basketItem: basketItem,
                            );
                          });
                    }
                  },
                  child: Text(
                    _status,
                    softWrap: true,
                    style: _status != '--'
                        ? Get.textTheme.titleLarge
                        : Get.textTheme.bodySmall,
                    overflow: TextOverflow.ellipsis,
                  ),
                ));
          } else if (dataGridCell.columnName == "When") {
            if (dataGridCell.value != null) {
              return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  DateFormat('yyyy-MM-dd kk:mm').format(
                      DateTime.fromMillisecondsSinceEpoch(dataGridCell.value)),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ),
              );
            } else {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    '--',
                    overflow: TextOverflow.ellipsis,
                  ));
            }
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value != null
                      ? dataGridCell.value.toString()
                      : "--",
                  softWrap: true,
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
